package com.lightsh.body;

import org.jbox2d.collision.shapes.PolygonDef;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.World;

import com.lightsh.utility.GeometryUtility;

import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.Rect;

class Rectangle extends PhysicsBody{

	private PolygonDef mPolygonDef;
	protected float mHalfW;
	protected float mHalfH;
	protected float[] mVertices;
	
	@Override
	public void draw(Canvas canvas, Rect screenRect, float selfScale, float worldScale) {
		super.draw(canvas,screenRect, selfScale, worldScale);		
		if(!isInRect(screenRect, selfScale)){
			return;
		}
		
		Vec2 vec2 = getPosition();
		canvas.save();
		rotateCanvas(canvas, mBody.getAngle(), vec2, screenRect, selfScale, worldScale);
		if(mSprite != null){
			mSprite.draw(canvas, mPaint, (int)((vec2.x - mHalfW) / selfScale + mDrawImageOffsetX - screenRect.left), (int)((vec2.y - mHalfH) / selfScale + mDrawImageOffsetY - screenRect.top), worldScale);
		}else if(mBitmap != null){
			drawBitmap(canvas, vec2.x - mHalfW, vec2.y - mHalfH, screenRect, selfScale, worldScale);
		}else{
			GeometryUtility.trackPolygonPath(mPath, vec2, mPolygonDef.vertices, mVertices, selfScale, worldScale, screenRect.left, screenRect.top);
			canvas.drawPath(mPath, mPaint);
		}
		
		canvas.restore();
	}

	@Override
	public void update() {
		super.update();
	}

	/**
	 * 使用meter为单位
	 * @param world 世界
	 * @param x 中心坐标x
	 * @param y 中心坐标y
	 * @param halfWidth 宽度一半
	 * @param halfHeight 高度一半
	 * @param density 密度
	 * @param friction 摩擦力
	 * @param restitution 碰撞后恢复系数
	 */
	public Rectangle(World world, float x, float y, float halfWidth,
			float halfHeight, float density, float friction, float restitution) {
		super(world);
		mPolygonDef = new PolygonDef();
		mPath = new Path();
		mPolygonDef.density = density;
		mPolygonDef.friction = friction;
		mPolygonDef.restitution = restitution;
		mHalfW = halfWidth;
		mHalfH = halfHeight;
		mPolygonDef.setAsBox(halfWidth, halfHeight);
		mBodyDef.position.x = x;
		mBodyDef.position.y = y;
		mVertices = new float[mPolygonDef.getVertexCount() << 1];
	}

	@Override
	public boolean isInRect(Rect rect, float scale) {
		Vec2 vec2 = getPosition();
		return GeometryUtility.isInRectCenter(vec2, mHalfW, mHalfH, rect, scale);		
	}
	
	@Override
	public boolean isUpperRect(Rect rect, float scale) {
		Vec2 vec2 = getPosition();
		return ((vec2.y + mHalfH) / scale) < rect.top;
	}

	@Override
	public void create() {
		super.create();
		mBody = mWorld.createBody(mBodyDef);
		mShape = mBody.createShape(mPolygonDef);
		mBody.setMassFromShapes();
	}
	
	
}
